package com.aruba.xfermodeapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * 心电图效果
 */
public class HearLineView extends View {
    private Bitmap bitmapSrc;
    private Paint mPaint = new Paint();
    private int dx;

    public HearLineView(Context context) {
        this(context, null);
    }

    public HearLineView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HearLineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        //使原图背景不透明
        Bitmap bitmapSrc1 = BitmapFactory.decodeResource(getResources(), R.mipmap.heartmap);
        bitmapSrc = Bitmap.createBitmap(bitmapSrc1.getWidth(), bitmapSrc1.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapSrc);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmapSrc1, 0, 0, new Paint());

        mPaint.setColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //使用SRC_IN
        canvas.drawRect(bitmapSrc.getWidth() - dx, 0, bitmapSrc.getWidth(), bitmapSrc.getHeight(), mPaint);

        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmapSrc, 0, 0, mPaint);
        mPaint.setXfermode(null);

        dx += 20;
        if (dx > bitmapSrc.getWidth()) dx = 0;
        postInvalidateDelayed(20);
    }
}
